package com.lysj.admin.master.common.spring.pagination;


import cn.hutool.core.util.StrUtil;
import com.lysj.admin.master.common.CommonConstant;
import com.lysj.admin.master.common.web.ParamUtil;
import lombok.Data;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;

import java.io.Serializable;

/**
 * @author Created by zk on 2019-12-05 2:36
 * @description
 */
@Data
public class PageRequestDTO implements Serializable {
    private int pageNumber;//页号

    private int pageSize;//页面大小

    private String pageSort;//排序字段

    private String pageOrder;//排序方式 asc/desc

    public PageRequestDTO() {
        initMpPage();
    }

    public PageRequestDTO(int pageNumber, int pageSize) {
        this.pageNumber = pageNumber;
        this.pageSize = pageSize;
        initMpPage();
    }

    public PageRequestDTO(int pageNumber, int pageSize, String pageSort, String pageOrder) {
        this.pageNumber = pageNumber;
        this.pageSize = pageSize;
        this.pageSort = pageSort;
        this.pageOrder = pageOrder;
        initMpPage();
    }

    private void initMpPage() {
        if (this.pageNumber < 1) {
            this.pageNumber = 1;
        }

        if (this.pageSize < 1) {
            this.pageSize = 10;
        }

        if (ParamUtil.isBlank(this.pageSort)) {
            this.pageSort = CommonConstant.CREATE_TIME_NAME;
        }

        if (ParamUtil.isBlank(this.pageOrder)) {
            this.pageOrder = "desc";
        }
    }

    public Pageable initPage() {
        Pageable pageable = null;
        int pageNumber = this.pageNumber;
        int pageSize = this.pageSize;
        String sort = this.pageSort;
        String order = this.pageOrder;
        if(pageNumber<1){
            pageNumber=1;
        }
        if(pageSize<1){
            pageSize=10;
        }
        if(StrUtil.isNotBlank(sort)) {
            Sort.Direction d;
            if(StrUtil.isBlank(order)) {
                d = Sort.Direction.DESC;
            }else {
                d = Sort.Direction.valueOf(order.toUpperCase());
            }
            Sort s = new Sort(d,sort);
            pageable = new PageRequest(pageNumber-1, pageSize,s);
        }else {
            Sort s = new Sort(Sort.Direction.DESC,CommonConstant.CREATE_TIME_NAME);
            pageable = new PageRequest(pageNumber-1, pageSize,s);
        }
        return pageable;
    }
}
